import { getOssToken } from '@/services/api/user/user';
import OSS from 'ali-oss';
let credentials: any = null;
function isCredentialsExpired(credentials: any) {
  if (!credentials) {
    return true;
  }
  const expireDate = new Date(credentials.expireDate);
  const now = new Date();
  return expireDate.getTime() - now.getTime() <= 60000;
}
export default async function getOss() {
  if (isCredentialsExpired(credentials)) {
    const res = await getOssToken();
    if (res.code === 200) {
      credentials = res.data;
    }
  }
  const client = new OSS({
    bucket: import.meta.env.VITE_OSS_BUCKET,
    region: import.meta.env.VITE_OSS_REGION,
    accessKeyId: credentials.AccessKeyId,
    accessKeySecret: credentials.AccessKeySecret,
    stsToken: credentials.SecurityToken,
  });
  return client;
}
